using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class BlockBackground : MonoBehaviour{
	
	public GameEngine engine;
	
	protected void Awake(){
		int x=0, y=0, xl=engine.gridWidth, yl=engine.gridHeight;
		Vector3[] vertices = new Vector3[(xl*yl)*4];
		Vector2[] uv = new Vector2[(xl*yl)*4];
		int[] triangles = new int[(xl*yl)*6];
		
		float w = engine.blockBounds.width;
		float h = engine.blockBounds.height;
		
		Vector3 offset = new Vector3(w*0.5f,h*0.5f,0);
			
		int i=0;
		for(; x<xl; ++x){
			for(y=0; y<yl; ++y){
				int vi = i*4;
				int ti = i*6;
				
				vertices[vi]   = new Vector3(x*w,y*h,0)-offset;
				vertices[vi+1] = new Vector3((x+1)*w,y*h,0)-offset;
				vertices[vi+2] = new Vector3(x*w,(y+1)*h,0)-offset;
				vertices[vi+3] = new Vector3((x+1)*w,(y+1)*h,0)-offset;
				
				uv[vi]   = new Vector2(0,0);
				uv[vi+1] = new Vector2(1,0);
				uv[vi+2] = new Vector2(0,1);
				uv[vi+3] = new Vector2(1,1);
				
				triangles[ti]   = vi;
				triangles[ti+1] = vi+2;
				triangles[ti+2] = vi+1;
				triangles[ti+3] = vi+1;
				triangles[ti+4] = vi+2;
				triangles[ti+5] = vi+3;
				
				++i;
			}
		}
		
		Mesh mesh = new Mesh();
		mesh.vertices = vertices;
		mesh.triangles = triangles;
		mesh.uv = uv;
		mesh.RecalculateNormals();
		
		GetComponent<MeshFilter>().mesh = mesh;
	}
	
}

